# coding=utf-8
"""
作者：董新强 
创建时间：2019-2-27
描述：ORM基类
"""
from datetime import datetime
from decimal import Decimal

from sqlalchemy.ext.declarative import declarative_base

from framework.utilities import to_list

BaseOrmClass = declarative_base()


class OrmBase():
    @staticmethod
    def get_dict(instance, format=True, tolist_fields=(), exclude_fields=(), convert_fields={}):
        '''
        获取模型实例的字典
        :param instance: 模型的实例
        :param format: 是否格式化
        :param tolist_fields: 需要转换为list的字段的列表
        :param exclude_fields: 排除字段
        :return: dict
        '''
        if not isinstance(instance, BaseOrmClass):
            return None

        if not isinstance(tolist_fields, (list, tuple)):
            tolist_fields = ()

        exclude = instance.exclude() if hasattr(instance, 'exclude') else ()
        Cl = type(instance)
        fields = Cl.metadata.tables[Cl.__tablename__].columns._data
        dic = {}

        for f in fields:  # 进行格式化
            if f in exclude or f in exclude_fields:
                continue
            val = getattr(instance, f)

            ###进行格式化#######################################
            showname = convert_fields.get(f) or f
            if format:
                if isinstance(val, (datetime, Decimal)):
                    dic[showname] = '' if not val else str(val)
                elif f in tolist_fields:
                    dic[showname] = to_list(val, [])
                else:
                    dic[showname] = val
            else:
                ###只是获取值##################################
                if f in tolist_fields:
                    dic[showname] = to_list(val, [])
                else:
                    dic[showname] = val

        return dic
